import {
	BitSet,
	BitClr,
	Set2Byte,
	DataGet,
	ab2hex,
	hexCharCodeToStr,
	arrayToBuffer,
	Parse,
	paraconfigdata,
	Set3Byte,
	bitToStr,
	Set1Byte,
	feedback,
	Set4Byte,
	Get2Byte,
	Get4Byte,
	Get3Byte,
	getByBite,
	hexToSignedDecimal,
	uploadEquipCommlog,hexStringToArray,
} from "@/utils/index.js";
import {
	masterMessage,
	binMessage,
	unitMessage,
	resultMessage,
} from "./message.js";
import {
	serviceId,
	characteristicId3,
} from "@/utils/service.js";

import {
	READ_AND_WRITE_STATUS,
} from "@/common/config.js";
import {
	 AESEncrypt
} from "@/utils/AesEncrypt.js";
export default {
	data() {
		return {
			startTime: null, //开始时间戳
		}
	},
	methods: {
		isRead() {
			let that = this;
			uni.showModal({
				title: '提示',
				content: '确定要查询吗？',
				success(res) {
					if (res.confirm) {
						that.doRead();
					}
				}
			})
		},
		// 读取设备信息
		async doRead(addr) {
			let that = this;
			that.$Toast.loading(`读取中...`);
			this.startTime = new Date().getTime();

			let datas = DataGet(this.command, 1, addr ? addr : 0, 0, 0, null);
			let buffer = arrayToBuffer(datas);
			let requestHex = ab2hex(buffer);

			let {
				deviceId,
			} = this.deviceInfo;
			uni.writeBLECharacteristicValue({
				deviceId,
				serviceId,
				characteristicId: characteristicId3,
				// 这里的value是ArrayBuffer类型
				value: buffer,
				success(res) {
					setTimeout(() => {
						that.doCharData(addr);
					}, 300)
					uploadEquipCommlog(requestHex, '', READ_AND_WRITE_STATUS[1], 1, that.startTime,
						that.deviceInfo, that.dgMessage);
				},
				fail(err) {
					console.log(err)
					that.$Toast.none(`${that.dgMessage}读取失败!`);
					uploadEquipCommlog(requestHex, '', READ_AND_WRITE_STATUS[1], 0, that.startTime,
						that.deviceInfo, that.dgMessage);
				}
			})
		},
		// 读取数据
		doCharData(addr) {
			let {
				deviceId,
			} = this.deviceInfo;
			let that = this;
			this.startTime = new Date().getTime();

			// 读取低功耗蓝牙设备的特征值的二进制数据值
			uni.readBLECharacteristicValue({
				deviceId,
				serviceId,
				characteristicId: characteristicId3,
				success(res) {
					uni.onBLECharacteristicValueChange(function(res) {
						uni.hideLoading();
						// 解析数据
						let buffer = res.value;
						const uint8Array = new Uint8Array(res.value);
						const newArray = Array.from(uint8Array);

						uploadEquipCommlog('', ab2hex(res.value), READ_AND_WRITE_STATUS[0], 1, that
							.startTime,
							that.deviceInfo, that.dgMessage);

						let databuff = Parse(newArray);
						switch (databuff.dataUnit) {
							//数据单元 0：主控单元;1：检测单元;2：仓控单元;3：柜控电源单元;4：整流电源单元;5：电池单元;6：消防单元;7：充电电源
							case 0:
								if (databuff.databuff && databuff.databuff.length == 23) {
									that.masterInfo.param1 = databuff.databuff[0];
									that.masterInfo.param2 = databuff.databuff[1];
									that.masterInfo.param3 = databuff.databuff[2];

									let str5 = ab2hex(buffer.slice(10, 30));
									that.masterInfo.param4 = hexCharCodeToStr(str5);
								}
								break;
							case 1:
								// 检测单元参数查询
								if (databuff.databuff && databuff.databuff.length == 11) {
									// 设置烟感反馈点
									that.unitInfo.param1 = databuff.databuff[0];
									// 设置维护门反馈数量
									that.unitInfo.param2 = databuff.databuff[1];
									// 设置维护门反馈点
									let param1 = getByBite(databuff.databuff[2]);
									that.unitInfo.param3 = param1[0];
									that.unitInfo.param4 = param1[1];
									that.unitInfo.param5 = param1[4];
									that.unitInfo.param6 = param1[5];

									that.unitInfo.param7 = databuff.databuff[3];
									that.unitInfo.param8 = databuff.databuff[4];
									that.unitInfo.param9 = databuff.databuff[5];
									that.unitInfo.param10 = databuff.databuff[6];

									// 过温点设置
									let param11 = ab2hex(buffer.slice(14, 16));
									that.unitInfo.param11 = param11 == '7fff' ? '不设置' :
										hexToSignedDecimal(param11);
									// 水流检测使能
									that.unitInfo.param12 = databuff.databuff[10];
									// 水箱水位检测使能
									that.unitInfo.param13 = databuff.databuff[11];
								}
								break;
							case 2:
								if (databuff.databuff && databuff.databuff.length == 4) {
									// 电锁反馈设置
									let param1 = getByBite(databuff.databuff[0]);
									param1.forEach((item, index) => {
										that.binDetail[`param${index}`] = item;
									})
									// 灭火器反馈设置
									let param2 = getByBite(databuff.databuff[1]);
									that.binDetail.param9 = param2[0];
									that.binDetail.param10 = param2[4];

									// 电锁反馈点数量
									that.binDetail.param11 = databuff.databuff[2];
									// 在位反馈设置
									let param3 = getByBite(databuff.databuff[3]);
									that.binDetail.param12 = param3[0];
									that.binDetail.param13 = param3[4];
								}
								break;
							case 3:
								if (databuff.databuff && databuff.databuff.length == 16) {
									that.cabenitInfo.param1 = hexToSignedDecimal(ab2hex(buffer.slice(7,
										9)));
									that.cabenitInfo.param2 = hexToSignedDecimal(ab2hex(buffer.slice(9,
										11)));
									that.cabenitInfo.param3 = hexToSignedDecimal(ab2hex(buffer.slice(11,
										13)));
									that.cabenitInfo.param4 = hexToSignedDecimal(ab2hex(buffer.slice(13,
										15)));

									let param1 = Get2Byte(databuff.databuff.slice(8, 10));
									that.cabenitInfo.param5 = (param1 / 100)
										.toFixed(2);
									let param2 = Get2Byte(databuff.databuff.slice(10, 12));
									that.cabenitInfo.param6 = (param2 / 100)
										.toFixed(2);
									let param3 = Get2Byte(databuff.databuff.slice(12, 14));
									that.cabenitInfo.param7 = (param3 / 100)
										.toFixed(2);

									that.cabenitInfo.param8 = Get2Byte(databuff.databuff.slice(14, 16));
								}

								break;
							case 4:
								if (databuff.databuff && databuff.databuff.length == 22) {
									that.powerInfo.param1 = hexToSignedDecimal(ab2hex(buffer.slice(7,
										9)));
									that.powerInfo.param2 = hexToSignedDecimal(ab2hex(buffer.slice(9,
										11)))
									that.powerInfo.param3 = hexToSignedDecimal(ab2hex(buffer.slice(11,
										13)));
									that.powerInfo.param4 = hexToSignedDecimal(ab2hex(buffer.slice(13,
										15)));

									that.powerInfo.param5 = Get2Byte(databuff.databuff.slice(8, 10));
									that.powerInfo.param6 = Get2Byte(databuff.databuff.slice(10, 12));
									that.powerInfo.param7 = Get2Byte(databuff.databuff.slice(12, 14));
									that.powerInfo.param8 = Get2Byte(databuff.databuff.slice(14, 16));

									let param1 = Get2Byte(databuff.databuff.slice(16, 18));
									that.powerInfo.param9 = (param1 / 100)
										.toFixed(2);
									let param2 = Get2Byte(databuff.databuff.slice(18, 20));
									that.powerInfo.param10 = (param2 / 100)
										.toFixed(2);

									that.powerInfo.param11 = Get2Byte(databuff.databuff.slice(20,
										22));
								}
								break;
							case 5:
								if (databuff.databuff && databuff.databuff.length == 36) {
									that.batteryInfo.param1 = Get2Byte(databuff.databuff.slice(0, 2));

									let param1 = Get2Byte(databuff.databuff.slice(2, 4));
									that.batteryInfo.param2 = (param1 / 100)
										.toFixed(2);

									that.batteryInfo.param3 = Get2Byte(databuff.databuff.slice(4, 6));
									that.batteryInfo.param4 = Get2Byte(databuff.databuff.slice(6, 8));
									that.batteryInfo.param5 = Get2Byte(databuff.databuff.slice(8, 10));
									that.batteryInfo.param6 = hexToSignedDecimal(ab2hex(buffer.slice(17,
										19)));
									that.batteryInfo.param7 = hexToSignedDecimal(ab2hex(buffer.slice(19,
										21)));

									let param2 = Get2Byte(databuff.databuff.slice(14, 16));
									that.batteryInfo.param8 = (param2 / 100)
										.toFixed(2);

									let param3 = Get2Byte(databuff.databuff.slice(16, 18));
									that.batteryInfo.param9 = (param3 / 100)
										.toFixed(2);

									let param4 = Get2Byte(databuff.databuff.slice(18, 20));
									that.batteryInfo.param10 = (param4 / 100)
										.toFixed(2);
									let param5 = Get2Byte(databuff.databuff.slice(20, 22));
									that.batteryInfo.param11 = (param5 / 100)
										.toFixed(2);
									let param6 = Get2Byte(databuff.databuff.slice(22, 24));
									that.batteryInfo.param12 = (param6 / 100)
										.toFixed(2);
									let param7 = Get2Byte(databuff.databuff.slice(24, 26));
									that.batteryInfo.param13 = (param7 / 100)
										.toFixed(2);
									let param8 = Get2Byte(databuff.databuff.slice(26, 28));
									that.batteryInfo.param14 = (param8 / 100)
										.toFixed(2);
									let param9 = Get2Byte(databuff.databuff.slice(28, 30));
									that.batteryInfo.param15 = (param9 / 100)
										.toFixed(2);
									let param10 = Get2Byte(databuff.databuff.slice(30, 32));
									that.batteryInfo.param16 = (param10 / 100)
										.toFixed(2);
									let param11 = Get2Byte(databuff.databuff.slice(32, 34));
									that.batteryInfo.param17 = (param11 / 100)
										.toFixed(2);
									let param12 = Get2Byte(databuff.databuff.slice(34, 36));
									that.batteryInfo.param18 = (param12 / 100)
										.toFixed(2);
								}
								break;
							case 7:
								if (databuff.databuff && databuff.databuff.length == 18) {
									that.chargeInfo.param1 = hexToSignedDecimal(ab2hex(buffer.slice(7,
										9)));;
									that.chargeInfo.param2 = hexToSignedDecimal(ab2hex(buffer.slice(9,
										11)));;
									that.chargeInfo.param3 = hexToSignedDecimal(ab2hex(buffer.slice(11,
										13)));;
									that.chargeInfo.param4 = hexToSignedDecimal(ab2hex(buffer.slice(13,
										15)));;

									let param1 = Get2Byte(databuff.databuff.slice(8, 10));
									that.chargeInfo.param5 = (param1 / 100)
										.toFixed(2);
									let param2 = Get2Byte(databuff.databuff.slice(10, 12));
									that.chargeInfo.param6 = (param2 / 100)
										.toFixed(2);
									let param3 = Get2Byte(databuff.databuff.slice(12, 14));
									that.chargeInfo.param7 = (param3 / 100)
										.toFixed(2);
									let param4 = Get2Byte(databuff.databuff.slice(14, 16));
									that.chargeInfo.param8 = (param4 / 100)
										.toFixed(2);
									that.chargeInfo.param9 = Get2Byte(databuff.databuff.slice(16, 18));
								}
								break;
						}
					})

				},
				fail(fal) {
					console.log("读取数据数据失败", fal)
					that.$Toast.none(`${that.dgMessage}读取失败!`);
					uploadEquipCommlog('', fal.errCode, READ_AND_WRITE_STATUS[0], 0, that.startTime,
						that.deviceInfo, that.dgMessage);
				}
			})
		},
		// 仓状态详情
		binPopup(index) {
			this.$refs.binpopup.open('center');
			this.currentIndex = index + 1;
			this.dgMessage = `${this.currentIndex}号仓`;
			for (let key of Object.keys(this.binDetail)) {
				this.binDetail[key] = "";
			}
			// 读取仓状态
			this.doRead(index);
		},
		powerPopup(index) {
			this.$refs.powerpopup.open('center');
			this.currentIndex = index + 1;
			this.command = 4;
			this.dgMessage = `整流电源${this.currentIndex}`;

			for (let key of Object.keys(this.powerInfo)) {
				this.powerInfo[key] = "";
			}
			// 读取仓状态
			this.doRead(index);
		},
		chargePopup(index) {
			this.$refs.chargepopup.open('center');
			this.currentIndex = index + 1;
			this.command = 7;
			this.dgMessage = `充电电源${this.currentIndex}`;

			for (let key of Object.keys(this.chargeInfo)) {
				this.chargeInfo[key] = "";
			}
			// 读取仓状态
			this.doRead(index);
		},
		cabinetPopup(index) {
			this.$refs.cabinetpopup.open('center');
			this.currentIndex = index + 1;
			this.command = 3;
			this.dgMessage = `柜控电源${this.currentIndex}`;

			for (let key of Object.keys(this.cabenitInfo)) {
				this.cabenitInfo[key] = "";
			}
			// 读取仓状态
			this.doRead(index);
		},
		unitPopup(index) {
			this.$refs.unitpopup.open('center');
			this.currentIndex = index + 1;
			this.command = 1;
			this.dgMessage = `检测单元${this.currentIndex}`;

			for (let key of Object.keys(this.unitInfo)) {
				this.unitInfo[key] = "";
			}
			// 读取仓状态
			this.doRead(index);
		},
		batteryPopup(index) {
			this.$refs.batterypopup.open('center');
			this.currentIndex = index + 1;
			this.command = 5;
			this.dgMessage = `电池${this.currentIndex}`;

			for (let key of Object.keys(this.batteryInfo)) {
				this.batteryInfo[key] = "";
			}
			// 读取仓状态
			this.doRead(index);
		},

		isSetting() {
			switch (this.type) {
				case "0": //主控参数
					// 判断是否为空,给出提示
					for (let i in this.masterInfo) {
						if (!this.masterInfo[i] && this.masterInfo[i] != '0') {
							this.$Toast.none(`${masterMessage[i]}为空！`);
							return;
						}
					}
					break;
				case "1": //仓控参数
					for (let i in this.binDetail) {
						if (!this.binDetail[i] && this.binDetail[i] != '0') {
							this.$Toast.none(`${binMessage[i]}为空！`);
							return;
						}
					}
					break;
				case "2": //检测单元参数
					for (let i in this.unitInfo) {
						if (!this.unitInfo[i] && this.unitInfo[i] != '0') {
							this.$Toast.none(`${unitMessage[i]}为空！`);
							return;
						}
					}
					break;
				case "3": //柜控电源
					for (let i in this.cabenitInfo) {
						if (!this.cabenitInfo[i] && this.cabenitInfo[i] != '0') {
							this.$Toast.none(`${cabenitMessage[i]}为空！`);
							return;
						}
					}
					break;
				case "4": //整流电源
					for (let i in this.powerInfo) {
						if (!this.powerInfo[i] && this.powerInfo[i] != '0') {
							this.$Toast.none(`${powerMessage[i]}为空！`);
							return;
						}
					}
					break;
				case "5": //充电电源
					for (let i in this.chargeInfo) {
						if (!this.chargeInfo[i] && this.chargeInfo[i] != '0') {
							this.$Toast.none(`${chargeMessage[i]}为空！`);
							return;
						}
					}
					break;
				case "6": //电池单元
					for (let i in this.batteryInfo) {
						if (!this.batteryInfo[i] && this.batteryInfo[i] != '0') {
							this.$Toast.none(`${batteryMessage[i]}为空！`);
							return;
						}
					}
					break;
			}

			let that = this;
			uni.showModal({
				title: '提示',
				content: '确定要设置参数吗？',
				success(res) {
					if (res.confirm) {
						that.doVerify();
					}
				}
			})
		},
		// 参数配置验证
		doVerify() {
			// 被发送的数据
			let sendData = [];
			switch (this.type) {
				case "0": //主控参数
					sendData = [this.masterInfo.param1, this.masterInfo.param2, this.masterInfo.param3, ...
						this.masterInfo
						.param4.split('')
					];
					break;
				case "1": //仓控参数
					let arr1 = [];
					for (let i = 0; i < 10; i++) {
						arr1.push(this.binDetail[param`${i + 1}`]);
					}

					let param2 = bitToStr([this.binDetail.param9, 0, 0, 0, this.binDetail.param10, 0, 0, 0]);
					let param4 = bitToStr([this.binDetail.param12, 0, 0, 0, this.binDetail.param13, 0, 0, 0]);
					sendData = [bitToStr(arr1), param2, this.binDetail.param11, param4];
					break;
				case "2": //检测单元参数
					let param3 = bitToStr([this.unitInfo.param3, this.unitInfo.param4, 0, 0, this.unitInfo
						.param5, this
						.unitInfo.param6, 0, 0
					]);
					sendData = [this.unitInfo.param1, this.unitInfo.param2, param3, this.unitInfo.param7, this
						.unitInfo
						.param8, this.unitInfo.param9, this.unitInfo.param10, ...Set2Byte(this.unitInfo
							.param11),
						this.unitInfo.param12, this.unitInfo.param13
					];
					break;
				case "3": //柜控电源
					sendData = [...Set2Byte(this.cabenitInfo.param1), ...Set2Byte(this.cabenitInfo.param2), ...
						Set2Byte(
							this.cabenitInfo.param3), ...Set2Byte(this.cabenitInfo.param4), ...Set2Byte(this
							.cabenitInfo.param5 * 100), ...Set2Byte(this.cabenitInfo.param6 * 10), ...
						Set2Byte(this
							.cabenitInfo.param7 * 10), ...Set2Byte(this.cabenitInfo.param8)
					];
					break;
				case "4": //整流电源 
					for (let i = 0; i < 8; i++) {
						sendData.push(this.powerInfo[param`${i + 1}`]);
					}
					let arr2 = [...Set2Byte(this.powerInfo.param9 * 100), ...Set2Byte(this.powerInfo.param10 *
							100), ...
						Set2Byte(this.powerInfo.param11)
					];
					sendData = [...sendData, ...arr2];
					break;
				case "5": //充电电源
					for (let i = 0; i < 4; i++) {
						sendData.push(this.powerInfo[param`${i + 1}`]);
					}
					for (let i = 4; i < 9; i++) {
						sendData.push(this.powerInfo[param`${i + 1}`] * 100);
					}
					sendData = [...sendData, ...Set2Byte(this.powerInfo.param9)];
					break;
				case "6": //电池单元 
					sendData = [...Set2Byte(this.batteryInfo.param1), ...Set2Byte(this.batteryInfo.param2 *
						100)];
					for (let i = 2; i < 8; i++) {
						sendData.push(...Set2Byte(this.powerInfo[param`${i + 1}`]));
					}
					for (let i = 7; i < 18; i++) {
						sendData.push(...Set2Byte(this.powerInfo[param`${i + 1}`] * 100));
					}
					break;
			}
			// 设置、控制： 被发送的数据需要进行加密
			let aesData = AESEncrypt(sendData.join(''));//加密数据
			console.log(sendData)
			console.log(sendData.join(''))
			console.log('对字符串进行AES加密处理结果--------')
			console.log(aesData)
			let decimalArray = aesData.match(/.{1,2}/g).map(hex => parseInt(hex, 16));
			console.log(decimalArray)
			console.log('数据区========')
			console.log(paraconfigdata(decimalArray))
			// dataUnit数据单元, operaType操作类型, addr地址, len数据区长度=rawbufflen+5, pack包号（单包取0，多包用上面的函数自动调用）, databuff数据区=snddatabuff整个数据区数组
			let datas = DataGet(this.command, 2, 0, decimalArray.length + 5, 0, paraconfigdata(decimalArray));

			this.doSetting(datas);
		},
		// 下发参数
		doSetting(datas) {
			console.log(datas)
			let buffer = arrayToBuffer(datas);
			console.log(ab2hex(buffer));
			let {
				deviceId,
			} = this.deviceInfo;
			// uni.writeBLECharacteristicValue({
			// 	deviceId,
			// 	serviceId,
			// 	characteristicId: characteristicId3,
			// 	// 这里的value是ArrayBuffer类型
			// 	value: buffer,
			// 	success(res) {
			// 		let value = hexCharCodeToStr(ab2hex(cpcl));
			// 		that.$Toast.none(value[resultMessage]);
			// 	},
			// 	fail(err) {
			// 		console.log(err)
			// 		that.$Toast.none(`${that.dgMessage}设置失败!`);
			// 	}
			// })
		},


	},
}